<?php
/***
 * 团购类
 */

class tuanHandler {
	
	/**
	 * 构造函数
	 * @param DBCA $dbca 数据库对象
	 */
    public function __construct($dbca){
        $this->dbca = $dbca;
    }
    
    /**
     * 查询团购分类信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     * 		'categoryID' => int 分类ID
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchTuanCategory( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //分类ID
        if (isset($arg_array['categoryID']) && is_numeric($arg_array['categoryID'])) {
            $sql .= ' AND categoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['categoryID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM tuan_category ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }
			
            
            //查询分类信息
            $search_sql = 'SELECT * FROM tuan_category ' . $sql;
            $temp_cate_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_cate_array)
                return null;

            foreach($temp_cate_array as &$cate) {
                $cate_array[] = array(
                    'uuid' => $cate->uuid,
                    'timeStamp' => $cate->timeStamp,
                    'creator' => $cate->creator,
                    'createTime' => $cate->createTime,
                    'categoryID' => $cate->categoryID,
                    'categoryName' => $cate->categoryName
                );
            }

            return $cate_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    
    /**
     * 添加或编辑团购分类
     * @param array $arg_array 参数数组
     * $arg_array = array ()
     * @return array
     */
    public function saveTuanCategory( $arg_array ) {
		
    	//分类名
        if (!isset($arg_array['categoryName']) || empty($arg_array['categoryName'])) {
        	return array( 'code' => 400, 'message' => '分类名不能为空' );
        }
        
        //创建者
        if (!isset($arg_array['creator']) || empty($arg_array['creator'])) {
        	return array( 'code' => 400, 'message' => '参数错误' );
        }
        
        try {
        	
			$tuan_category = new entity('tuan_category');
			
			if (isset($arg_array['categoryID']) && !empty($arg_array['categoryID'])) { //编辑
				$tuan_category->categoryID = $arg_array['categoryID'];
				if (!$this->dbca->fetch($tuan_category)) {
					return array( 'code' => 406, 'message' => '编辑对象没有找到');
				}
			}
			
			$tuan_category->creator = $arg_array['creator'];
			$tuan_category->categoryName = $arg_array['categoryName'];
		 	$this->dbca->save($tuan_category,'tuan');
		 	
		 	return array( 'code' => 200, 'message' => '保存成功' ); 
        	
        } catch (Exception $e) {
        	error_log($e->getMessage());
        	return array( 'code' => 500, 'message' => '系统异常,请与系统管理员联系' ); 
        }
    }
    
    /**
     * 删除团购分类信息
     *
     * @param array $arg_array
     * @return array
     */
    public function deleteTuanCategory( $arg_array ) {

        if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (empty($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '请选择要删除的团购分类' );

        $delete_array = explode('_', $arg_array['delete_str']);

        try {

            foreach($delete_array as &$tuan_category_id) {

                if (!is_numeric($tuan_category_id))
                    return array( 'code' => 400, 'message' => '参数错误' );

                //删除团购分类
                $tuan_category = new entity('tuan_category');
                $tuan_category->categoryID = $tuan_category_id;
                if ($this->dbca->fetch($tuan_category)) {
                    $this->dbca->delete($tuan_category);
                }
            }

            return array( 'code' => 200, 'message' => '删除成功' );

        } catch (Exception $e) {

            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );

        }

    }
    
     /**
     * 查询团购信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     * 		'categoryID' => int 分类ID
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchTuanInfo( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //团购ID
        if (isset($arg_array['tid']) && is_numeric($arg_array['tid'])) {
            $sql .= ' AND tid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['tid'];
        }
        
        //团购ID
        if (isset($arg_array['channel']) && is_numeric($arg_array['channel'])) {
            $sql .= ' AND channel = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['channel'];
        }
        
        //团购标题
        if (isset($arg_array['groupon_title']) && !empty($arg_array['groupon_title'])) {
            $sql .= ' AND groupon_title = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['groupon_title'];
        }
        
        //开始日期
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND start_time >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
        }
        
        //结束日期
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND end_time <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] . ' 23:59:059';
        }
        
        //扩展查询
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM tuan_info ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }
			
            
            //查询分类信息
            $search_sql = 'SELECT * FROM tuan_info ' . $sql;
            $temp_tuan_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_tuan_array)
                return null;
            
            //获取团购所属城市
            $cityList = $this->getCity();
            
            //获取团购分类
            $arg_count_array = array();
            $tuanCategory = $this->searchTuanCategory( $arg_count_array );

            foreach($temp_tuan_array as &$tuan) {
            	
            	//获取团购分类名称
            	if (!empty($tuanCategory)) {
            		foreach ($tuanCategory as $cate) {
            			if ($cate['categoryID'] == $tuan->channel) {
            				$channelName = $cate['categoryName'];
            			}
            		}
            	}
            	
                $tuan_array[] = array(
                    'uuid' => $tuan->uuid,
                    'timeStamp' => $tuan->timeStamp,
                    'creator' => $tuan->creator,
                    'createTime' => $tuan->createTime,
                    'channel' => $tuan->channel,
                    'channelName' => $channelName,
                    'tid' => $tuan->tid,
                    'city' => $tuan->city,
                    'cityName' => $cityList[$tuan->city],
                    'postID' => $tuan->postID,
                    'mainPostID' => $tuan->mainPostID,
                    'goodsID' => $tuan->goodsID,
                    'goodsName' => $tuan->goodsName,
                    'goodsType' => $tuan->goodsType,
                    'cart_flg' => $tuan->cart_flg,
                    'groupon_title' => $tuan->groupon_title,
                    'groupon_brief' => $tuan->groupon_brief,
                    'groupon_price' => $tuan->groupon_price,
                    'orginal_price' => $tuan->orginal_price,
                    'low_limit' => $tuan->low_limit,
                    'total_limit' => $tuan->total_limit,
                    'detail_img_count' => $tuan->detail_img_count,
                    'start_time' => $tuan->start_time,
                    'end_time' => $tuan->end_time,
                    'out_lowlimit' => $tuan->out_lowlimit,
                    'groupon_detail' => $tuan->groupon_detail,
                    'buyers' => $tuan->buyers,
                    'f_buyers' => $tuan->f_buyers,
                    'r_buyers' => $tuan->r_buyers,
                    'a_buyers' => $tuan->a_buyers,
                    'last_buy_time' => $tuan->last_buy_time,
                    'followers' => $tuan->followers,
                    'deliver_fee' => $tuan->deliver_fee,
                    'discount' => round($tuan->groupon_price / $tuan->orginal_price, 2) * 10, //折扣
                    'saved_money' => $tuan->orginal_price - $tuan->groupon_price,	//优惠金额
                    'main_pic' => $this->getMainPic($tuan->tid), //主图
                    'detail_pic' => $this->getDetailPic( $tuan->tid, $tuan->detail_img_count), //详情图
                    'link' => $this->setGrouponLink($tuan->tid),	//shop链接
                    'wapLink' => $this->setGrouponWapLink($tuan->tid)	//wap链接
                );
            }

            return $tuan_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    
    /**
     * 获取团购城市
     *
     */
    public function getCity() {
    	$city = array(
            1 => "全国",
            2 => "北京",
            3 => "上海",
            4 => "广州"
        );
        return $city;
    }
    
	/**
     * 查询团购商品
     * @param array $arg_array 参数数组
     * @return null
     */
    public function searchTuanGoods( $arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //团购号
        if (isset($arg_array['tid']) && is_numeric($arg_array['tid'])) {
            $sql .= ' AND tid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['tid'];
        }
        
        //网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['postID'];
        }

        //扩展查询
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {
            //查询商品信息
            $search_sql = 'SELECT T_g.*,ps.goodsName,ps.product_code FROM (
							SELECT uuid,creator,createTime,tid,postID,goodsID,goods_spec1,goods_spec2,goodsMainPic,
							spec1_specID,spec2_specID,spec1_specGroupID,spec2_specGroupID,buy_limit,buy_count
							FROM tuan_goods ' . $sql . ') AS T_g
							 INNER JOIN goods_sale ps ON ps.postID = T_g.postID';
            $temp_goods_array = $this->dbca->stmt_query($search_sql, $params_type, $params_array);
	        if (!$temp_goods_array)
	            return null;
			
	        foreach($temp_goods_array as &$goods_obj) {
	            $goods_array[] = array(
	                'uuid' => $goods_obj->uuid,
	                'creator' => $goods_obj->creator,
	                'createTime' => $goods_obj->createTime,
	                'tid' => $goods_obj->tid,
	                'postID' => $goods_obj->postID,
	                'goodsID' => $goods_obj->goodsID,
	                'goods_spec1' => $goods_obj->goods_spec1,
	                'goods_spec2' => $goods_obj->goods_spec2,
	                'goodsMainPic' => '/quanliadmin/docroot/images/goods/' . $goods_obj->goodsMainPic,
	                'spec1_specID' => $goods_obj->spec1_specID,
	                'spec2_specID' => $goods_obj->spec2_specID,
	                'spec1_specGroupID' => $goods_obj->spec1_specGroupID,
	                'spec2_specGroupID' => $goods_obj->spec2_specGroupID,
	                'buy_limit' => $goods_obj->buy_limit,
	                'buy_count' => $goods_obj->buy_count,
	                'goodsName' => $goods_obj->goodsName,
	                'product_code' => $goods_obj->product_code
	            );
	        }
			
			return $goods_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }
    }
	
	/*统计订单数
	*return array($count_all,$count_ok,$count_no)
	*$count_all 总订单数
	*$count_ok  以支付的订单数
	*$count_no  未支付的订单数
	*/
	public function tuanBillCount( $tid ){
		$num = array();
				
		//全部的订单数
        $cntsql = "SELECT COUNT(*) count FROM tuan_bill WHERE goods_tuanID = ?";
        $countall = $this->dbca->stmt_query($cntsql, 'i', $tid);
		$count_all = $countall[0]->count;
		
		//统计已支付的订单数
		$sqlStr_ok = ' SELECT COUNT(*) count FROM tuan_bill WHERE bill_status=1 AND goods_tuanID = ?';
        $countok = $this->dbca->stmt_query($sqlStr_ok, 'i', $tid);
		$count_ok = $countok[0]->count;
		
		//统计未支付的订单数
		$sqlStr_no = ' SELECT COUNT(*) count FROM tuan_bill WHERE bill_status=0 AND goods_tuanID = ?';
        $countno = $this->dbca->stmt_query($sqlStr_no, 'i', $tid);
		$count_no = $countno[0]->count;
		
		//汇总
		$num = array($count_all,$count_ok,$count_no);
		return $num;
	}
	
	/**
     * 查询团购订单
     *
     */
    public function searchTuanBill( &$arg_array ) {
    	
    	//sql字符串
        $sql = '';
		
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
		
        //商品所属的团购
        if (isset($arg_array['goods_tuanID']) && !empty($arg_array['goods_tuanID']) && is_numeric($arg_array['goods_tuanID'])) {
        	$sql .= ' AND goods_tuanID = ?';
        	$params_type .= 'i';
        	$params_array[] = $arg_array['goods_tuanID'];
        }
        
        //订单号
        if (isset($arg_array['bill_tuanNo']) && !empty($arg_array['bill_tuanNo']) && is_numeric($arg_array['bill_tuanNo'])) {
        	$sql .= ' AND bill_tuanNo = ?';
        	$params_type .= 's';
        	$params_array[] = $arg_array['bill_tuanNo'];
        }
		
        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }
        
        $tuan_bill_list = array(); //账户异动日志数据数组
		
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM  tuan_bill ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
            }

            //查询分类信息
            $search_sql = 'SELECT * FROM tuan_bill '. $sql;
            $tuan_bill_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            
            if ($tuan_bill_array) {
            	foreach ($tuan_bill_array as $bill) {
            		$tuan_bill_list[] = array(
            			'uuid' => $bill->uuid,
            			'timeStamp' => $bill->timeStamp,
            			'creator' => $bill->creator,
            			'createTime' => $bill->createTime,
            			'bill_tuanNo' => $bill->bill_tuanNo,
            			'bill_creator' => $bill->bill_creator,
            			'bill_time' => $bill->bill_time,
            			'bill_money' => $bill->bill_money,
            			'bill_paid' => $bill->bill_paid,
            			'bill_memo' => $bill->bill_memo,
            			'bill_status' => $bill->bill_status,
            			'bill_pcustID' => $bill->bill_pcustID,
            			'bill_sysno' => $bill->bill_sysno,
            			'deliver_id' => $bill->deliver_id,
            			'deliver_reciever' => decryptD($bill->deliver_reciever),
            			'deliver_province' => $bill->deliver_province,
            			'deliver_city' => $bill->deliver_city,
            			'deliver_county' => $bill->deliver_county,
            			'deliver_address' => decryptD($bill->deliver_address),
            			'deliver_postalcode' => $bill->deliver_postalcode,
            			'deliver_mobile' => $bill->deliver_mobile,
            			'deliver_phone' => decryptD($bill->deliver_phone),
            			'deliver_email' => $bill->deliver_email,
            			'deliver_recievetime' => $bill->deliver_recievetime,
            			'deliver_manner' => $bill->deliver_manner,
            			'deliver_mannername' => $bill->deliver_mannername,
            			'deliver_time' => $bill->deliver_time,
            			'deliver_fee' => $bill->deliver_fee,
            			'deliver_status' => $bill->deliver_status,
            			'pay_time' => $bill->pay_time,
            			'pay_code' => $bill->pay_code,
            			'pay_type' => $bill->pay_type,
            			'payTypeID' => $bill->payTypeID,
            			'payTypeName' => $bill->payTypeName,
            			'pay_confirmer' => $bill->pay_confirmer,
            			'pay_confirmtime' => $bill->pay_confirmtime,
            			'pay_status' => $bill->pay_status,
            			'goods_id' => $bill->goods_id,
            			'goods_postID' => $bill->goods_postID,
            			'goods_tuanID' => $bill->goods_tuanID,
            			'goods_name' => $bill->goods_name,
            			'goods_spec' => $bill->goods_spec,
            			'goods_orginalprice' => $bill->goods_orginalprice,
            			'goods_tuanprice' => $bill->goods_tuanprice,
            			'goods_amount' => $bill->goods_amount,
            			'goods_lackpflg' => $bill->goods_lackpflg,
            			'goodsLink' => '/shop/goods-' . $bill->goods_postID . '.html'
            		);
            	}
            }
			
            return $tuan_bill_list;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }
    }
    
    /**
     * 删除团购信息
     *
     * @param array $arg_array
     * @return array
     */
    public function deleteTuanInfo( $arg_array ) {

        if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        if (empty($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '请选择要删除的团购分类' );

        $delete_array = explode('_', $arg_array['delete_str']);

        try {

            foreach($delete_array as &$tid) {
				
                if (!is_numeric( $tid ))
                    throw new Exception('参数错误', -1000);
				
                
                //删除团购信息
                $tuan_info = new entity('tuan_info');
                $tuan_info->tid = $tid;
                if ($this->dbca->fetch($tuan_info)) {
                	$this->dbca->delete($tuan_info);
                	
                	$sql = 'delete from tuan_goods where tid=?';
                	$this->dbca->stmt_query($sql,'i',$tid);
                	
                	$sql = 'delete from tuan_shipping where tid=?';
                	$this->dbca->stmt_query($sql,'i',$tid);
                	
                } else {
                	throw new Exception('团购信息不存在，请核对后再进行操作', -1000);
                }
            }
			
            return array( 'code' => 200, 'message' => '团购信息删除成功' );
			
        } catch (Exception $e) {
			if ($e->getCode() == -1000) {
				return array( 'code' => 406, 'message' => $e->getMessage());
			} else {
				error_log($e->getMessage());
	            return array( 'code' => 500, 'message' => '系统错误' );
			}
        }

    }
    
    /**
     * 保存团购信息
     * @param array $arg_array 参数数组
     * $arg_array = array ()
     * @return array
     */
    public function saveTuanInfo( $arg_array ) {
		
    	//所属分类
    	if (!isset($arg_array['category']) || !is_numeric($arg_array['category'])) {
    		return array( 'code' => 400, 'message' => '请选择团购所属分类' );
    	}
    	
    	//所在城市
    	if (!isset($arg_array['city']) || !is_numeric($arg_array['city'])) {
    		return array( 'code' => 400, 'message' => '请选择团购所在城市' );
    	}
    	
    	//团购价格
    	if (!isset($arg_array['groupon_price']) || !is_numeric($arg_array['groupon_price'])) {
    		return array( 'code' => 400, 'message' => '团购价格不能为空' );
    	} else {
    		$groupon_price = $arg_array['groupon_price'];
    	}
    	
    	//成团人数
    	if (!isset($arg_array['low_limit']) || !is_numeric($arg_array['low_limit'])) {
    		return array( 'code' => 400, 'message' => '成团人数不能为空' );
    	}
    	
    	//默认运费
    	if (!isset($arg_array['moren_yunfei']) || !is_numeric($arg_array['moren_yunfei'])) {
    		return array( 'code' => 400, 'message' => '默认运费不能为空' );
    	}
    	
    	//团购标题
    	if (!isset($arg_array['groupon_title']) || empty($arg_array['groupon_title'])) {
    		return array( 'code' => 400, 'message' => '团购标题不能为空' );
    	}
    	
    	//团购活动时间
    	if (!isset($arg_array['startDate'], $arg_array['endDate']) || empty($arg_array['startDate']) || empty($arg_array['endDate'])) {
    		return array( 'code' => 400, 'message' => '请完善团购活动时间' );
    	}
    	
    	//是否通过购物车购买
    	if (!isset($arg_array['cart_flg']) || !is_numeric($arg_array['cart_flg'])) {
    		return array( 'code' => 400, 'message' => '请选选择购买方式' );
    	}
    	
    	//团购基本信息
    	$category = $arg_array['category']; //分类
    	$city = $arg_array['city'];	 //城市
    	$groupon_price = $arg_array['groupon_price'];  //团购价格
    	$low_limit = $arg_array['low_limit']; 	//成团人数
    	$moren_yunfei = $arg_array['moren_yunfei']; //运费
    	$groupon_title = $arg_array['groupon_title']; //标题
    	$cart_flg = $arg_array['cart_flg'];	//购买方式
    	$startDate = $arg_array['startDate'];	//开始时间
		$endDate = $arg_array['endDate'];	//结束时间
		$groupon_brief = $arg_array['groupon_brief']; //团购简述
		
		//团购商品信息
		$tuan_goods_arr = array(); //团购商品数组
		$total_limit = 0; //团购允许的总共购买数
		if (isset($arg_array['goodsPostID']) && !empty($arg_array['goodsPostID'])) {
			foreach ($arg_array['goodsPostID'] as $postVal) {
				
				//判断团购商品数量是否有效
				if (!isset($arg_array['goods_num_'.$postVal]) || empty($arg_array['goods_num_'.$postVal])) {
					return array( 'code' => 400, 'message' => '所选团购商品的购买个数不能为空' );
				}
				
				//判断商品数量是否大于库存
				if ($arg_array['goods_num_'.$postVal] > $arg_array['goods_store_'.$postVal]) {
					return array( 'code' => 400, 'message' => '所选团购商品的购买个数不能大于该商品库存' );
				}
				
				$tuan_goods_arr[$postVal] = $arg_array['goods_num_'.$postVal];
				
				$total_limit += $arg_array['goods_num_' . $postVal];
			}
		} else {
			return array( 'code' => 400, 'message' => '商品必须为选中状态' );
		}
		
    	//团购详情页
    	$description = isset($arg_array['description']) ? $arg_array['description'] : '';
    	
    	//团购图片
    	//(1).团购主图片
    	$picName = isset($arg_array['picName']) ? $arg_array['picName'] : '';
    	
    	//(2).团购详情图片
        $detailPic = isset($arg_array['detailPic']) ? $arg_array['detailPic'] : '';
        
        try {
        	$this->dbca->beginTransaction();
        	
        	//查询商品信息是否存在
        	$goods_list = new entity('goods_list');
        	$goods_list->product_code = $arg_array['product_code'];
        	if (!$this->dbca->fetch($goods_list)) {
        		return array( 'code' => 406, 'message' => '团购商品信息不存在' );
        	}
			        	
        	//保存主商品信息
        	$tuan_info = new entity('tuan_info');
        	$tuan_info->creator = $arg_array['creator'];
        	$tuan_info->channel = $category;
        	$tuan_info->city = $city;
        	$tuan_info->postID = $goods_list->postID;
        	$tuan_info->mainPostID = $goods_list->mainPostID;
        	$tuan_info->goodsID = $goods_list->goodsID;
        	$tuan_info->goodsName = $goods_list->goodsName;
        	$tuan_info->cart_flg = $cart_flg;
        	$tuan_info->groupon_title = $groupon_title;
        	$tuan_info->groupon_brief = $groupon_brief;
        	$tuan_info->groupon_price = $groupon_price;
        	$tuan_info->orginal_price = $goods_list->salePrice;
        	$tuan_info->low_limit = $low_limit;
        	$tuan_info->total_limit = $total_limit;
        	$tuan_info->detail_img_count = count($detailPic);
        	$tuan_info->start_time = $startDate.' 00:00:00';
        	$tuan_info->end_time = $endDate.' 23:59:59';
        	$tuan_info->groupon_detail = $description;
        	$tuan_info->buyers = 0;
            $tuan_info->f_buyers = 0;
            $tuan_info->r_buyers = 0;
            $tuan_info->a_buyers = 0;
            $tuan_info->followers = 0;
            $tuan_info->deliver_fee = $moren_yunfei;
            $tuanInfo_saveFlg = $this->dbca->save($tuan_info,'tuan');
            
            if (!$tuanInfo_saveFlg) {
            	throw new Exception('团购主表信息保存失败', -1000);
            }
            
        	//获取最新写入的tid号
            $tid = $this->dbca->insert_id;
            
        	//团购主图片
            $dir = $tid; //区分每个团购商品的目录（以团购号命名文件夹）
            if ($picName != '') {
                $pictureLink = 'tuan/' . $this->uploadImg($tid, $dir);
            }
            
            //团购详情图片
            $detail_img_count = $this->doUploadDetailImg($detailPic, $tid);
            
            //保存团购商品信息
            if ($tuan_goods_arr) {
            	foreach ($tuan_goods_arr as $pV=>$gN) {
            		
            		$goods_sale = new entity('goods_sale');
            		$goods_sale->postID = $pV;
            		if (!$this->dbca->fetch($goods_sale)) {
            			throw new Exception('商品信息不存在', -1000);
            		}
            		
            		$specArr = $this->getSpec( $goods_sale->goodsID );
            		
            		$tuan_goods = new entity('tuan_goods');
            		$tuan_goods->tid = $tid;
                    $tuan_goods->creator = $arg_array['creator'];
                    $tuan_goods->postID = $goods_sale->postID;
                    $tuan_goods->goodsID = $goods_sale->goodsID;
                    $tuan_goods->goods_spec1 = $specArr['specName1'];
                    $tuan_goods->goods_spec2 = $specArr['specName2'];
                    $tuan_goods->spec1_specID = $specArr['specID1'];
                    $tuan_goods->spec2_specID = $specArr['specID2'];
                    $tuan_goods->spec1_specGroupID = $specArr['specGroupID1'];
                    $tuan_goods->spec2_specGroupID = $specArr['specGroupID2'];
                    $tuan_goods->goodsMainPic = $goods_sale->goodsMainPic;
                    $tuan_goods->buy_limit = $gN;
                    $tuan_goods->buy_count = 0;
                    $this->dbca->save($tuan_goods, 'tuan');
            	} 
            }
            
            //运费tuan_shipping
            if ($arg_array['tuanFee']) {
            	foreach ($arg_array['tuanFee'] as $fk=>$fv) {
            		if (empty($fv)) {
            			unset($arg_array['tuanFee'][$fk]);
            		}
            		
            		foreach ($arg_array['tuanFee'][$fk] as $province_id) {//获取每个运费文本框的值，然后分别写入数据库
            			
            			$sys_region = new entity('sys_region');
            			$sys_region->id = $province_id;
            			if (!$this->dbca->fetch($sys_region)) {
            				throw new Exception('区域不存在', -1000);
            			}
            			
            			//保存运费信息
            			$tuan_shipping = new entity('tuan_shipping');
            			$tuan_shipping->creator = $arg_array['creator'];
            			$tuan_shipping->tid = $tid;
            			$tuan_shipping->provinceName = $sys_region->name;
                        $tuan_shipping->provinceid = $province_id;
                        $tuan_shipping->shipping_fee = $fk;
                        $tuan_shipping->editor = $arg_array['creator'];
                        $this->dbca->save($tuan_shipping, "tuan");
                    }
            	}
            }
        	
            //提交事务
            $this->dbca->commit();
            
            return array( 'code' => 200, 'message' => '团购保存成功' );
        	
        } catch (Exception $e) {
        	
        	//事务回滚
        	$this->dbca->rollBack();
        	
        	if ($e->getCode() == -1000) {
        		return array( 'code' => 406, 'message' => $e->getMessage() ); 
        	} else {
        		return array( 'code' => 500, 'message' => '系统错误，请联系网站管理员');
        	}
        }
    }
    
    //获取规格信息
    private function getSpec($goodsID) {
        $arr = array();
        global $G_PGLOB;
        $sqlstr = sprintf(' where goods_spec_relation.goodsID=%d ', $goodsID);

        $sql = 'SELECT gsr.specID,gs.specName,gsg.specGroupID 
					FROM goods_spec_relation gsr 
					JOIN goods_spec_group gsg ON gsr.specGroupID = gsg.specGroupID
					JOIN goods_spec gs ON gsr.specID = gs.specID
					WHERE gsr.goodsID = ? ORDER BY gsg.sortOrder';
        
        $specs = $G_PGLOB->DBCA->stmt_query($sql,'i',$goodsID);
        if ($specs) {
            $arr = array(
                'specID1' => isset($specs[0]->specID) ? $specs[0]->specID : '',
                'specName1' => isset($specs[0]->specName) ? $specs[0]->specName : '',
                'specGroupID1' => isset($specs[0]->specGroupID) ? $specs[0]->specGroupID : '',
                'specID2' => isset($specs[1]->specID) ? $specs[1]->specID : '',
                'specName2' => isset($specs[1]->specName) ? $specs[1]->specName : '',
                'specGroupID2' => isset($specs[1]->specGroupID) ? $specs[1]->specGroupID : '',
            );
        }
        return $arr;
    }
    
    /**
     * 团购主图片上传函数（上传单个）
     * 2011年11月7日  尹福林
     * @param  $tid 团购号
     * @return 
     */
    private function uploadImg($tid, $dir) {
        try {
            $savePath = G_APPLICATION_BASEPATH . 'quanliadmin/docroot/images/tuan/';   //团购图片保存路径
            $tmpPath = G_APPLICATION_BASEPATH . 'quanliadmin/docroot/images/tmp/';   //团购图片临时路径
            $uploadfileName = $_REQUEST['picName'];           //团购图片原文件名(文件名+扩展名)

            if ($uploadfileName != '') {
                $imgExt = strtolower(substr($uploadfileName, strpos($uploadfileName, '.'), 6)); //获取文件的扩展名，并转化为小写			
                $imgName = 'tuan_' . $tid . '_main';

                $fileName = $savePath . $dir . '/' . $imgName . $imgExt;       //组成新的文件名

                if (!file_exists($savePath . $dir . '/')) {          //判断目录是否存在，若不存在则建立
                    mkdir($savePath . $dir . '/', 0777,true);         //目录结构为：tuan/$tid/tuan_$tid_main.jpg
                }

                if (file_exists($fileName) && file_exists($savePath . $uploadfileName)) {//如果要上传的文件在目录下有相同名称的文件存在，
                    @unlink($fileName);            //则将同名的文件删除
                }


                $flg = rename($tmpPath . $uploadfileName, $fileName);      //将文件移到指定目录下

                return $dir . '/' . $imgName . $imgExt;
            } else {
                return '';
            }
        } catch (Exception $e) {
            //error_log($e->getMessage());
            throw new Exception($e->getMessage());
        }
    }
    
    /*
     * 详情图片上传
     * 2011年11月8日 尹福林
     * @param  $detUploadFile	表单处理后提交过来的数据
     * @param  $tid				最新写入数据库的团购号
     * @return $detail_count_img 返回处理成功的图片个数
     */

    private function doUploadDetailImg($detUploadFile, $tid) {

        $n = 0;
        $maxN = 0;

        //处理已经上传的图片
        $n = ++$maxN;

        //对图片进行计数
        $detail_img_count = 0;

        //处理新上传的图片
        if ($detUploadFile) {
            foreach ($detUploadFile as &$detLine) {
                $file_ext = strtolower(substr(strrchr($detLine, '.'), 1));
                $fileName = 'tuan_' . $tid . '_detail_' . $n . '.' . $file_ext;

                //移动图片并得到图片名称
                $pictureLink = $this->uploadDetailImg($tid, $fileName, $detLine);

                if ($pictureLink != "") {  //如果移动图片到指定目录成功，则$detail_count_img+1
                    $detail_img_count +=1;
                }
                $n++;
            }
        }
        return $detail_img_count;
    }
    
    /*
     * 移动图片上传图片到指定目录
     * 2011年11月8日 尹福林
     * @param  $tid	团购号
     * @param  $fileName 指定的文件名（上传后）
     * @param  $uploadfileName	上传的文件名（上传前）
     * 			$tid 团购号命名的目录（每个相同团购号的商品放在同一个目录下）
     * @return 
     */

    private function uploadDetailImg($tid, $fileName, $uploadfileName) {
        global $G_PGLOB;
        try {
            $savePath = G_APPLICATION_BASEPATH . 'quanliadmin/docroot/images/tuan/';
            $tmpPath = G_APPLICATION_BASEPATH . 'quanliadmin/docroot/images/tmp/';

            if (!file_exists($savePath . $tid . '/')) {
                mkdir($savePath . $tid . '/', 0777,true);
            }

            //防止页面刷新
            if (!file_exists($tmpPath . $uploadfileName)) {//如果临时文件夹中，不存在要上传的文件
                return $tid . '/' . $fileName;
            }

            if (($savePath . $tid . '/' . $fileName)) {  //如果目标文件夹下存在与上传前的文件名重名的文件，则删除目标文件夹中重名的文件
                @unlink($savePath . $tid . '/' . $fileName);
            }

            //将图片移动到指定目录
            rename($tmpPath . $uploadfileName, $savePath . $tid . '/' . $fileName);

            return $tid . '/' . $fileName;
        } catch (Exception $e) {
            //error_log($e->getMessage());
            $G_PGLOB->smarty->display('comm/errorDisplay.tpl');
        }
    }
    
    /**
     * 获取团购主图
     *
     * @param int $tid 团购号
     * @return string
     */
    public function getMainPic ( $tid ) {
    	return '/quanliadmin/docroot/images/tuan/'.$tid.'/tuan_' . $tid . '_main.jpg';
    }
    
    /**
     * 获取团购详情图片
     *
     * @param int $tid 团购号
     * @param int $count 详情图片数量
     */
    public function getDetailPic ( $tid, $count ) {
    	$detailArr = array();
    	
    	for ( $i=1; $i<=$count; $i++) {
    		$detailArr[] = '/quanliadmin/docroot/images/tuan/'.$tid.'/tuan_'.$tid.'_detail_'.$i.'.jpg';
    	}
    	
    	return $detailArr;
    }
    
    /**
     * 设置团购链接
     *
     * @param int $tid 团购号
     * @return string
     */
    public function setGrouponLink ( $tid ) {
    	return '/shop/groupon_detail-' . $tid .'.html';
    }
    
    /**
     * 设置团购WAP链接
     *
     * @param int $tid 团购号
     * @return string
     */
    public function setGrouponWapLink ( $tid ) {
    	return '/wap/groupon_detail-' . $tid .'.html';
    }
    
    /**
     * 获取团购商品的第一组规格信息
     * 
     * @param int $tid 团购号
     */

    public function getGrouponGoodsSpec1( $tid ) {
        
    	$sql = 'SELECT goodsMainpic,goods_spec1,spec1_specID,spec2_specID,spec1_specGroupID,postID 
    				FROM tuan_goods WHERE tid=? GROUP BY spec1_specID';
    	$tuanGoodsSpec1 = &$this->dbca->stmt_query($sql,'i',$tid);
		
    	$specArr = array();
    	
    	$i = 0;
    	if ($tuanGoodsSpec1) {
    		foreach ($tuanGoodsSpec1 as $spec1) {
    			$specArr[$i]['postID'] = $spec1->postID;
    			$specArr[$i]['spec1_specID'] = $spec1->spec1_specID;
    			$specArr[$i]['spec1Name'] = $spec1->goods_spec1;
    			$specArr[$i]['goodsPic'] = '/quanliadmin/docroot/images/goods/'.$spec1->goodsMainpic;
    		}
    	}
    	
        return $specArr;
    }
    
    /**
     * 根据收货地址查询配送方式【团购结算】
     * @param array $arg_array 参数数组
     * @return null
     */
    public function loadSendType( $arg_array ) {
    	
    	//查询运费信息
    	$ship_array = $this->searchTuanShipping( $arg_array );
    	
    	//判断查询结果
    	if (isset($ship_array[0]) && !empty($ship_array[0])) {
    		$feight = $ship_array[0]['shipping_fee'];
    	} else {
    		$feight = 10;
    	}
		
    	//数组拼装
        $item_array[] = array(
            'sendTypeID' => 4,
            'sendTypeName' => '快递',
            'send_region_id' => 0,
            'send_region_name' => '',
            'freight' => $feight,
            'description' => '快递',
        );
		
        //返回结果
        return $item_array;
    }
    
    /**
     * 查询团购商品
     * @param array $arg_array 参数数组
     * @return null
     */
    public function searchTuanShipping( $arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        
        //团购号
        if (isset($arg_array['tid']) && is_numeric($arg_array['tid'])) {
            $sql .= ' AND tid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['tid'];
        }

        //省ID
        if (isset($arg_array['provinceid']) && is_numeric($arg_array['provinceid'])) {
            $sql .= ' AND provinceid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['provinceid'];
        }
        
        //市ID
        if (isset($arg_array['cityid']) && is_numeric($arg_array['cityid'])) {
            $sql .= ' AND cityid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityid'];
        }
        
        //区ID
        if (isset($arg_array['countyid']) && is_numeric($arg_array['countyid'])) {
            $sql .= ' AND districtid = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['countyid'];
        }
        
        //扩展查询
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }
		
        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {
            //查询商品信息
            $search_sql = 'SELECT * FROM tuan_shipping ' . $sql;
            $temp_ship_array = $this->dbca->stmt_query($search_sql, $params_type, $params_array);
	        if (!$temp_ship_array)
	            return null;
			
	        foreach($temp_ship_array as &$ship) {
	            $ship_array[] = array(
	                'uuid' => $ship->uuid,
	                'timeStamp' => $ship->timeStamp,
	                'creator' => $ship->creator,
	                'createTime' => $ship->createTime,
	                'tid' => $ship->tid,
	                'provinceName' => $ship->provinceName,
	                'cityName' => $ship->cityName,
	                'districtName' => $ship->districtName,
	                'provinceid' => $ship->provinceid,
	                'cityid' => $ship->cityid,
	                'districtid' => $ship->districtid,
	                'shipping_fee' => $ship->shipping_fee,
	                'editor' => $ship->editor
	            );
	        }
			
			return $ship_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }
    }
    
    /**
     * 根据配送方式查询支付方式【团购结算】
     * @param $arg_array
     * @return null
     */
    public function loadPayType( &$arg_array ) {

        $search_sql = 'SELECT * FROM sys_sendtype_pay WHERE sendTypeID = ? AND pay_type = 2';

        $pay_type_array =& $this->dbca->stmt_query($search_sql, 'i', $arg_array['sendTypeID']);
        if (!$pay_type_array)
            return null;

        foreach($pay_type_array as &$item) {

            $item_array[] = array(
                'sendTypeID' => $item->sendTypeID,
                'type' => $item->pay_type
            );

        }

        return $item_array;

    }
    
    /**
     * 保存团购订单
     *
     * @param array $arg_array 参数数组
     * 
     */
    public function saveTuanBill( $arg_array ) {
    	
    	//判断团购号是否有效
    	if (!isset($arg_array['tid']) || !is_numeric($arg_array['tid'])) {
    		return array( 'code' => 400, 'message' => '该秒杀不存在' );
    	}
    	
    	//判断团购商品或者规格不存在
    	if (!isset($arg_array['pid']) || !is_numeric($arg_array['pid'])) {
    		return array( 'code' => 400, 'message' => '该秒杀商品或者规格不存在' );
    	}
    	
    	//收货地址
    	if (!isset($arg_array['deliverID']) || !is_numeric($arg_array['deliverID'])) {
    		return array( 'code' => 400, 'message' => '请填写或选择收货地址');
    	}
    	
    	//送货时间
    	if (!isset($arg_array['send_time']) || empty($arg_array['send_time'])) {
    		return array( 'code' => 400, 'message' => '请选择送货时间' );
    	}
    	
    	//配送方式
    	if (!isset($arg_array['sendTypeID']) || !is_numeric($arg_array['sendTypeID'])) {
    		return array( 'code' => 400, 'message' => '请选择配送方式');
    	}
    	
    	//支付类型
    	if (!isset($arg_array['payType']) || !is_numeric($arg_array['payType'])) {
    		return array( 'code' => 400, 'message' => '请选择支付类型');
    	}
    	
    	//支付方式
    	if (!isset($arg_array['payTypeID']) || !is_numeric($arg_array['payTypeID'])) {
    		return array( 'code' => 400, 'message' => '请选择支付方式');
    	}
    	
    	//实例化公共类
    	$commHandler = new commHandler( $this->dbca );
		    	
    	try {
    		
    		//开启事务
    		$this->dbca->beginTransaction();
    		
    		//更新增加实际参团人数
    		$sql = 'UPDATE tuan_info SET buyers=buyers+1 WHERE tid = ?';
    		$this->dbca->stmt_query($sql,'i',$arg_array['tid']);
    		
    		//查询团购是否存在
    		$tuan_info = new entity('tuan_info');
    		$tuan_info->tid = $arg_array['tid'];
    		if (!$this->dbca->fetch($tuan_info)) {
    			throw new Exception('该秒杀不存在', -1000);
    		}
    		
    		//查看参团人数是否超过参团限制
    		if ($tuan_info->buyers > $tuan_info->total_limit) {
    			throw new Exception('对不起，该商品团购库存不足，请选择其他团购', -1000);
    		}
    		
    		//查找验证收货地址
    		$cust_deliver = new entity('cust_deliver');
    		$cust_deliver->deliverID = $arg_array['deliverID'];
    		if (!$this->dbca->fetch($cust_deliver)) {
    			throw new Exception('请填写或选择收货地址', -1000);
    		}
    		
    		//检查运费
    		$arg_ship_array = array(
    			'tid' => $arg_array['tid'],
    			'provinceid' => $cust_deliver->provinceid
    		);
    		$tuanShipping = $this->loadSendType( $arg_ship_array );
    		if (!isset($tuanShipping[0]) || empty($tuanShipping[0])) {
    			throw new Exception('运费查询失败', -1000);
    		}
    		
    		$tuanShipping = $tuanShipping[0];
    		
    		//验证支付方式
    		$sys_paytype = new entity('sys_paytype');
    		$sys_paytype->payTypeID = $arg_array['payTypeID'];
    		if (!$this->dbca->fetch($sys_paytype)) {
    			throw new Exception('支付方式没有找到', -1000);
    		}
    		
			    		
    		//检查团购商品是否存在
    		$tuan_goods = new entity('tuan_goods');
    		$tuan_goods->tid = $arg_array['tid'];
    		$tuan_goods->postID = $arg_array['pid'];
    		if (!$this->dbca->fetch($tuan_goods)) {
    			throw new Exception('该秒杀商品或者规格不存在', -1000);
    		}
			
    		//生成团购订单号
            $tuan_bill_no = $commHandler->generate_seqno('seqno_bill');
            
            //实例化团购订单表
            $tuan_bill = new entity('tuan_bill');
            $tuan_bill->creator = $arg_array['creator'];
            $tuan_bill->createTime = $arg_array['createTime'];
            $tuan_bill->bill_tuanNo = $tuan_bill_no;
            $tuan_bill->bill_creator = $arg_array['creator'];
            $tuan_bill->bill_time = $arg_array['createTime'];
            $tuan_bill->bill_money = $tuan_info->groupon_price;
            $tuan_bill->bill_memo = '';
            $tuan_bill->bill_status = 0;
            $tuan_bill->bill_pcustID = $arg_array['pcustID'];
            $tuan_bill->deliver_id = $arg_array['deliverID'];
            $tuan_bill->deliver_reciever = $cust_deliver->custName;
            
            $tuan_bill->deliver_province = $cust_deliver->provinceName;
			$tuan_bill->deliver_city = $cust_deliver->cityName;
			$tuan_bill->deliver_county = $cust_deliver->countyName;
			$tuan_bill->deliver_address = $cust_deliver->address;
			
			$tuan_bill->deliver_postalcode = $cust_deliver->postalCode;
			$tuan_bill->deliver_mobile = $cust_deliver->mobile;
			$tuan_bill->deliver_phone = $cust_deliver->phone;
			$tuan_bill->deliver_email = $cust_deliver->email;
			$tuan_bill->deliver_recievetime = $arg_array['send_time'];
			$tuan_bill->deliver_manner = $tuanShipping['sendTypeID'];
			$tuan_bill->deliver_mannername = $tuanShipping['sendTypeName'];
			$tuan_bill->deliver_fee = $tuanShipping['freight'];
			$tuan_bill->deliver_status = 0;
			
			$tuan_bill->pay_type = $arg_array['payType'];			//支付类型
			$tuan_bill->payTypeID = $sys_paytype->payTypeID;		//支付方式ID
			$tuan_bill->payTypeName = $sys_paytype->payTypeName;	//支付方式名称
			
			$tuan_bill->pay_status = 0;
			$tuan_bill->bill_paid = $tuan_bill->bill_money + $tuan_bill->deliver_fee;
			$tuan_bill->goods_id = $tuan_goods->goodsID;
			$tuan_bill->goods_postID = $tuan_goods->postID;
			$tuan_bill->goods_tuanID = $tuan_goods->tid;
			$tuan_bill->goods_name = $tuan_info->goodsName;
			$tuan_bill->goods_spec = $tuan_goods->goods_spec1.' '.$tuan_goods->goods_spec2;
			$tuan_bill->goods_orginalprice = $tuan_info->orginal_price;
			$tuan_bill->goods_tuanprice = $tuan_info->groupon_price;
			$tuan_bill->goods_amount = 1;
			
			//保存订单 
			$this->dbca->save($tuan_bill,'tuan');
			
			//更新参团总人数,用于页面显示"参团人数"
			$sql = 'UPDATE tuan_info SET a_buyers = buyers + f_buyers + r_buyers WHERE tid=?';
			$this->dbca->stmt_query($sql, 'i', $arg_array['tid']);
			
			//更新最后一次参团时间
			$sql = 'UPDATE tuan_info SET last_buy_time="'.$arg_array['createTime'].'" WHERE tid=?';
			$this->dbca->stmt_query($sql, 'i', $arg_array['tid']);
			
			//更新团购商品已购买数量
			$sql = 'UPDATE tuan_goods SET buy_count=buy_count+1 WHERE tid=? AND postID=?';
			$this->dbca->stmt_query($sql, 'ii', array($arg_array['tid'],$arg_array['pid']));
			
			//提交事务
    		$this->dbca->commit();
    		
			return array( 'code' => 200, 'message' => '团购订单保存成功', 'data' => array('bill_no' => $tuan_bill_no) );
    		
    	} catch (Exception $e) {
    		//事务回滚
    		$this->dbca->rollBack();
    		if ($e->getCode() == -1000) {
    			return array( 'code' => 406, 'message' => $e->getMessage() );
    		} else {
    			return array( 'code' => 500, 'message' => '系统错误，请联系网站管理员' );
    		}
    	}
    	
    }
    
    /**
     * 手动调节参团人数
     *
     */
    public function saveJoinPerson( $arg_array ) {
    	
    	//判断团购号
    	if (!isset($arg_array['tid']) || !is_numeric($arg_array['tid'])) {
    		return array( 'code' => 400, 'message' => '参数错误' );
    	}
    	
    	//调节的数量
    	if (!isset($arg_array['count']) || !is_numeric($arg_array['count'])) {
    		return array( 'code' => 400, 'message' => '参数错误' );
    	}
    	
    	//判断数量是否有效
    	if ($arg_array['count'] < 0) {
    		return array( 'code' => 400, 'message' => '数量必须大于0' );
    	}
    	
    	try {
			$tuan_info = new entity('tuan_info');
			$tuan_info->tid = $arg_array['tid'];
			if (!$this->dbca->fetch($tuan_info)) {
				throw new Exception('该团购不存在', -1000);
			}
			
			$tuan_info->f_buyers = $arg_array['count'];
			$tuan_info->a_buyers = $arg_array['count'] + $tuan_info->r_buyers + $tuan_info->buyers;
			$this->dbca->save($tuan_info, 'tuan');
			
			return array( 'code' => 200, 'message' => '保存成功' );
					
    	} catch (Exception $e) {
    		if ($e->getCode() == -1000) {
    			return array( 'code' => 406, 'message' => $e->getMessage() );
    		} else {
    			return array( 'code' => 500, 'message' => '系统错误，请联系网站管理员' );
    		}
    	}
    }
    
    /**
     * 添加关注
     *
     */
    public function setAttention( $arg_array ) {
    	
    	if (!isset($arg_array['tid']) || !is_numeric($arg_array['tid'])) {
    		die( json_encode( array( 'code' => 400, 'message' => '参数错误' ) ) );
    	}
    	
    	if (!isset($arg_array['pcustID']) || !is_numeric($arg_array['pcustID'])) {
    		die( json_encode( array( 'code' => 400, 'message' => '请先登录' ) ) );
    	}
    	
    	try {
    		//判断团购是否存在
			$tuan_info = new entity('tuan_info');
			$tuan_info->tid = $arg_array['tid'];
			if (!$this->dbca->fetch($tuan_info)) {
				throw new Exception('该团购不存在', -1000);
			}
			
			//查询用户信息
			$cust_master = new entity('cust_master');
			$cust_master->pcustID = $arg_array['pcustID'];
			if (!$this->dbca->fetch($cust_master)) {
				throw new Exception('用户信息不存在', -1000);
			}
			
			//保存团购关注
			$tuan_alert = new entity('tuan_alert');
			$tuan_alert->tid = $arg_array['tid'];
			$tuan_alert->pcustID = $arg_array['pcustID'];
			if ($this->dbca->fetch($tuan_alert)) {
				return array( 'code' => 200, 'message' => '已关注' );
			}
			$tuan_alert->creator = $arg_array['creator'];
			$tuan_alert->cust_email = $cust_master->email;
			$tuan_alert->cust_mobile = $cust_master->mobile;
			$tuan_alert->send_title = $tuan_info->groupon_title;
			$tuan_alert->send_content = $tuan_info->start_time;
			$tuan_alert->send_time = $tuan_info->start_time;
			
			$this->dbca->save($tuan_alert,'tuan');
			
			return array( 'code' => 200, 'message' => '关注成功' );
					
    	} catch (Exception $e) {
    		if ($e->getCode() == -1000) {
    			return array( 'code' => 406, 'message' => $e->getMessage() );
    		} else {
    			return array( 'code' => 500, 'message' => '系统错误，请联系网站管理员' );
    		}
    	}
    	
    	
    }

}